<?php
declare (strict_types = 1);

namespace app\command;

use app\api\consDir\CommunityConst;
use app\common\models\Community\CommunityUser;
use app\common\models\Community\PrepayCommunityOrder;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class PrepayCommunityUser extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('prepay:community')
            ->setDescription('the prepay community user command');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $where = [
            ['status','=',2],
            ['community_id','=',0]
        ];
        $list = PrepayCommunityOrder::getInstance()->where($where)->select();
        if(empty($list)){
           return false;
        }
        foreach($list as $v){
            PrepayCommunityOrder::getInstance()->startTrans();
            try{
                $where = [
                    ['lock_status','=',1],
                    ['community_status','=',CommunityConst::RELEASE_STATUS],
                    ['type','=',0],
                    ['user_id','<>',$v->user_id]
                ];
                $communityUser = CommunityUser::getInstance()->where($where)->order('last_enter_amount asc')->find();
                if(empty($communityUser)){
                    continue;
                }
                $communityUser->type = 4;
                $communityUser->update_at = date('Y-m-d H:i:s');
                $communityUser->save();
                $v->community_id = $communityUser->community_id;
                $v->update_at = date('Y-m-d H:i:s');
                $v->save();
                PrepayCommunityOrder::getInstance()->commit();
            }catch (\Exception $e){
                PrepayCommunityOrder::getInstance()->rollback();
                $output->writeln($e->getMessage());
            }
        }
        // 指令输出
        $output->writeln('prepay community user');
    }
}
